package com.lfsenior.mq;

import redis.clients.jedis.Jedis;

import java.util.Set;

/**
 * Created by dlupan on 2018/10/11
 *
 * 持久订阅
 */
public class PPubClient {
    private Jedis jedis;
    private String CONSTANT = "clientSet";
    public PPubClient(String host,int port){
        jedis = new Jedis(host,port);
    }

    /**
     * 以set的形式持久
     * @param message
     */
    private void put(String message){
        Set<String> subClients = jedis.smembers(CONSTANT);
        for(String clientKey:subClients){
            jedis.rpush(clientKey, message);
        }
    }

    /**
     * 向指定频道发送内容并持久化
     * @param channel
     * @param message
     */
    public void pub(String channel,String message){
        //获取增长的数值
        Long txid = jedis.incr("MAXID");
        String content = txid+"/"+message;
        //存储内容
        this.put(content);
        //发布消息
        jedis.publish(channel, message);
    }

    /**
     * 删除当前频道
     * @param channel
     */
    public void close(String channel){
        jedis.publish(channel, "quit");
        jedis.del(channel);
    }

}
